import { Injectable } from '@nestjs/common';
import { CreateDictSonDto } from './dto/create-dict-son.dto';
import { UpdateDictSonDto } from './dto/update-dict-son.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { DictSon } from './entities/dict-son.entity';
import { Repository } from 'typeorm';
import { PageQuery } from '../../../util/entity/page.entity';
import { buildQuery } from '../../../util/common-fn';

@Injectable()
export class DictSonService {
  constructor(
    @InjectRepository(DictSon)
    private dictSonRepository: Repository<DictSon>,
  ) {}

  create(createDictSonDto: CreateDictSonDto) {
    return this.dictSonRepository.save(createDictSonDto);
  }

  findAll() {
    return this.dictSonRepository.find();
  }

  findOne(id: number) {
    return this.dictSonRepository.findOneBy({ id });
  }

  findOneWithDict(id: number) {
    return this.dictSonRepository.findOne({
      where: { id },
      relations: {
        dict: true,
      },
    });
  }

  update(id: number, updateDictSonDto: UpdateDictSonDto) {
    return this.dictSonRepository.update({ id }, updateDictSonDto);
  }

  async remove(id: number) {
    await this.dictSonRepository.findOneByOrFail({ id });
    return this.dictSonRepository.softDelete({ id });
  }

  // 检查添加dictSon的code是否重复
  async checkAddCodeUnique(code: number, dictId: number) {
    const existDictSon = await this.getByCodeAndDictId(code, dictId);
    if (existDictSon) {
      throw new Error(`编码${code}已存在`);
    }
  }

  // 检查编辑dictSon的code是否重复
  async checkEditCodeUnique(code: number, dictId: number, preCode: number) {
    const existDictSon = await this.getByCodeAndDictId(code, dictId);
    if (existDictSon && code !== preCode) {
      throw new Error(`编码${code}已存在`);
    }
  }

  async getByCodeAndDictId(code: number, dictId: number) {
    return await this.dictSonRepository.findOneBy({
      code,
      dict: {
        id: dictId,
      },
    });
  }

  /**
   * 通过父code和子code,获取子code对应的name
   */
  async getNameByCode(parentCode: string, sonCode: number) {
    const dictSon = await this.dictSonRepository.findOneBy({
      dict: {
        code: parentCode,
      },
      code: sonCode,
    });
    if (dictSon) {
      return dictSon.name;
    } else {
      throw new Error('找不到字典表的名称');
    }
  }

  async findListByDictId(dictId: number, pageQuery: PageQuery<DictSon>) {
    const extraWhere = {
      dict: {
        id: dictId,
      },
    };
    return await this.dictSonRepository.findAndCount(
      buildQuery(pageQuery, extraWhere),
    );
  }
}
